import { BankCard, BankCardFunding, CurrencyCode, Recipient, RecipientType, Withdrawal, WithdrawalService } from "@mallfoundry/finance"
import { Button, Card, Divider, Form, Input, InputNumber, Radio, Select, Skeleton, Tabs, Typography } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { useHistory, useParams } from "react-router-dom"
import Page from "../../components/page"
import { useAccount, useBalance, useBankCards } from "../../hooks/finance"
import { useStore } from "../../hooks/store"
import { messageError } from "../../utils/reason"
import classes from "./withdrawal-apply.module.scss"

const { TextArea } = Input

const { Text } = Typography

const { TabPane } = Tabs

const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 4 },
}

const tailLayout = {
  wrapperCol: { offset: 2, span: 4 },
}

export default function WithdrawalApply() {
  const history = useHistory()
  const { storeId } = useParams<{ storeId: string }>()
  const [confirmLoading, setConfirmLoading] = useState(false)
  const { loading: storeLoading, store: { accountId } } = useStore(storeId)
  const { loading: accountLoading, account } = useAccount(accountId)
  const { loading: balanceLoading, balance } = useBalance(accountId, CurrencyCode.CNY)
  const { loading: bankCardsLoading, elements: bankCards } = useBankCards({ accountId })
  const loading = storeLoading || accountLoading || balanceLoading

  function handleApply(values: any) {
    const { amount, memo } = values
    const bankCard = _.find(bankCards, card => card.id === values.recipient) as BankCard
    const {
      holderType, holderName,
      bankName, branchName, number,
    } = bankCard
    const withdrawal = _.assign(new Withdrawal(), {
      accountId, amount, memo,
      currency: CurrencyCode.CNY,
      recipient: _.assign(new Recipient(), {
        type: RecipientType.BankCard,
        holderType, holderName,
        name: holderName,
        bankName, branchName,
        number,
      }),
    })

    setConfirmLoading(true)
    WithdrawalService
      .applyWithdrawal(withdrawal)
      .then(aWithdrawal => {
        setConfirmLoading(false)
        history.push(`/stores/${storeId}/withdrawals/${aWithdrawal.id}/progress`)
      })
      .catch(reason => {
        messageError(reason)
        setConfirmLoading(false)
      })
  }

  function renderRecipientSelectOption(card: BankCard) {
    const cardText = []
    cardText.push(card.bankName)
    if (card.funding === BankCardFunding.Debit) {
      cardText.push("储蓄卡")
    } else if (card.funding === BankCardFunding.Credit) {
      cardText.push("信用卡")
    }
    cardText.push("(")
    cardText.push(card.last4)
    cardText.push(")")
    return _.join(cardText, "")
  }

  return (
    <div className={classes.WithdrawalApply}>
      <Page.Header title="提现" ghost={false}/>
      <Page.Content loading={loading}>
        <Card>
          <Tabs activeKey="1" animated={false} onChange={tabKey => {
            if (tabKey === "2") {
              history.push(`/stores/${storeId}/withdrawals`)
            }
          }}>
            <TabPane tab="提现" key="1">
              <Form name="withdrawal-form" {...layout} initialValues={{ amount: 1 }} onFinish={handleApply}>
                <Form.Item label="账户名称">
                  {loading ? <Skeleton.Input style={{ width: "160px" }} active/> : <span className="ant-form-text">{account.name}</span>}
                </Form.Item>
                <Form.Item required label="付款来源">
                  <Radio checked>店铺余额</Radio>
                </Form.Item>
                <Form.Item label="可提现金额">
                  {loading ? <Skeleton.Input style={{ width: "160px" }} active/> :
                    <Text className="ant-form-text" type="danger">{balance.availableAmount} 元</Text>}
                </Form.Item>
                <Form.Item label="提现金额" required>
                  <Form.Item name="amount" noStyle rules={[{ required: true, message: "提现金额不能为空" }]}>
                    <InputNumber style={{ width: "160px" }} min={0.01} max={balance.availableAmount} precision={2}/>
                  </Form.Item>
                  <Button type="link">全部提现</Button>
                </Form.Item>
                <Form.Item label="到账银行卡" name="recipient" rules={[{ required: true, message: "请选择到账银行卡" }]}>
                  <Select loading={bankCardsLoading} dropdownRender={menu => (
                    <>
                      {menu}
                      <Divider style={{ margin: "4px 0" }}/>
                      <Button type="link" block>添加银行卡</Button>
                    </>
                  )}>
                    {_.map(bankCards, bankCard => (
                        <Select.Option key={bankCard.id}
                                       value={bankCard.id as string}>{renderRecipientSelectOption(bankCard)}</Select.Option>
                      ),
                    )}
                  </Select>
                </Form.Item>
                <Form.Item label="备注" name="memo">
                  <TextArea autoSize={{ minRows: 3, maxRows: 6 }}/>
                </Form.Item>
                <Form.Item {...tailLayout}>
                  <Button type="primary" htmlType="submit"
                          loading={confirmLoading}>提现</Button>
                </Form.Item>
              </Form>
            </TabPane>
            <TabPane tab="提现记录" key="2"/>
          </Tabs>
        </Card>
      </Page.Content>
    </div>
  )
}
